var request;
var korSize = 12;
var nonSize = 10;
var pageBand = 0;
var jsonData;
var jsonData_Schema;
var jsonData_DB;
var jsonData_Table;

var countLimit;
var rowCount;
var workingDB;
var workingTable;

var eData; // excelData;
var pkData;
var pkArray = new Array();
var key;
var startIdx = 0;
var textLength; // java script can't use Array by Parameter.
var offsetL = 0;

var COLOR_TR_ODD = "#CCCCCC";
var COLOR_TR_EVEN = "#EEEEEE";
var COLOR_TR_UPDATE = "#FF8888";
var COLOR_TR_DELETE = "#666666";

var COLOR_FONT_NORMAL = "#000000";
var COLOR_FONT_UPDATE = "#FF0000";
var COLOR_INPUT_AUTO = "#BBBBBB";

var MARGIN_LEFT_SCHEMA_TREE = 24;
var BIGSIZEROW = 100;
var queryStringInputed = new Array();
var url;
var sql;
var offsetI = 1;

var pagingValue = 0;

function JSonData(request) {
	this.rData;
	this.InfoSchema;
	this.InfoDB;
	this.InfoTable;

	rData = eval('(' + request.responseText + ')');

	if (1) {
		InfoSchema = rData;
	} else if (1) {
		InfoDB = rData;
		workingDB;
	} else if (1) {
		InfoTable = rData;
		workingDB;
		workingTable;
	}
}

// ajax�� �̿��ؼ� ��� �ε��ϴ� �ϴ� ���� "�ε��̹���"�� on / off
function loading(status) {
	var loadingImage = document.getElementById("loadingImage");
	if (status == "on") {
		loadingImage.style.display = "block";
	} else if (status == "off") {
		loadingImage.style.display = "none";
	}
}

function runAjax(query, object) {
	var query_B = query;
	/*
	 * if (query.match(patt)) { for ( var i = 0; i < query.length - 5; i++) { if
	 * (query.substring(i, i + 5) == "limit") { query_B = query.substring(0, i); } } }
	 */
	var querys = lTrim(query).split(" ");

	var queryType = querys[0].toLowerCase();
	var schema = document.getElementById("DBselector").value;

	url = "./servlet/QueryBrowser.do";
	url += "?query=" + query_B;
	url += schema != "" ? "&schema=" + schema : "";
	url += "&count=yes";
	url += "&dummy=" + new Date().getTime();

	// ==== http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequesteventtarget ====
	// createRequest();
	request = getXMLHTTPRequest();

	request.open("Get", url, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status == 200) {
			var usePaging = document.getElementById("usePaging");
			var useAjax = document.getElementById("useAjax");
			rowCount = eval('(' + request.responseText + ')');
			countLimit = document.getElementById("countLimit").value;

			// useAjax.checked

			if (rowCount > countLimit) {
				if (usePaging.checked && useAjax.checked || !usePaging.checked) {
					var message = "There are so many result (" + rowCount + " records).";
					message += "\n\nThis works may take a long time.";
					message += "\n\nDo you want to somehow progress it?";
					if (confirm(message)) {
						goQuery(query, object);
					} else {
						message = "unsing Ajax, send query at once.";
						message += "\n\ncheck  'using paging'.";
						message += "\n\nuncheck  'use Ajax'.";
						message += "\n\nthen, each page send query respectively.";
						alert(message);
					}
				} else {
					goQuery(query, object);
				}
			} else {
				goQuery(query, object);
			}

		}
	};

	request.send(null);
}

function goQuery(query, object) {
	var querys = lTrim(query).split(" ");
	var queryType = querys[0].toLowerCase();
	var schema = document.getElementById("DBselector").value;

	var useAjax = document.getElementById("useAjax");
	var usePaging = document.getElementById("usePaging");
	var patt = /limit/gi;

	if (query.match(patt) && usePaging.checked) {
		var message = "If you want to use limit keyword, ";
		message += "uncheck paging option.";
		alert(message);
		return;
	}

	pagingValue = Number(document.getElementById("pagingValue").value);
	if (queryType == "select") {
		if (usePaging.checked && !useAjax.checked) {
			query = query.replace(";", "");
			query += " limit " + (offsetI - 1) * pagingValue;
			query += ", " + pagingValue;
			query += ";";
		}
	}

	url = "./servlet/QueryBrowser.do";
	url += "?query=" + query;
	url += schema != "" ? "&schema=" + schema : "";
	url += "&count=no";
	url += "&dummy=" + new Date().getTime();

	request = getXMLHTTPRequest();

	if (queryType == "show" || queryType == "select" || queryType == "describe") {
		if (schema == "" && queryType == "select") {
			alert("No database selected.");
			return false;
		}
		request.open("Get", url, true);
		loading("on");
		request.onreadystatechange = function() {
			if (request.readyState == 4 && request.status == 200) {
				loading("off");
				if (object != "") {
					showSchemata(query, object);
				} else {
					retrieve(startIdx);
				}
			}
		};
	} else {
		request.open("Post", url, true);
		request.onreadystatechange = function() {
			loading("off");
			if (object != "") {
				alert(queryType + " : 1");
			} else {
				alert(queryType + " : 2");
			}
		};
	}
	request.send(null);
}

function setDB(sname) {
	document.getElementById("schema").value = sname.split("@")[0];

	var DBselector = document.getElementById("DBselector");
	var options = DBselector.getElementsByTagName("option");
	for ( var i = 0; i < options.length; i++) {
		if (sname.split("@")[0] == options[i].value) {
			options[i].selected = true;
		}
	}
	workingDB = document.getElementById("schema").value;
}

function showSchemata(sql, parent) {
	var queryTarget = lTrim(sql).split(" ");
	var ul = document.createElement("ul");
	ul.id = queryTarget[1];
	ul.className = "list";

	if (request.readyState == 4) {
		jsonData = eval('(' + request.responseText + ')');

		for ( var i = 0; i < jsonData.data[1].resultSet.length; i++) {
			var columnName = jsonData.data[0].columnNames[0];
			var text = String(eval("jsonData.data[1].resultSet[" + i + "]." + columnName));

			var li = document.createElement("li");
			li.id = text + "@" + parent.id;

			if (queryTarget[0] == "show" && queryTarget[1] == "databases") { // =============
				// describe
				li.className = "schema_plus";
				var textNode = document.createTextNode(text);

				li.onclick = function() {
					document.getElementById("schema").value = getText(this);
					if (this.className == "schema_plus") {
						this.className = "schema_minus";

						// ------------- toggle on / off
						var uls = this.parentNode.getElementsByTagName("ul");
						for ( var i = 0; i < uls.length; i++) {
							uls[i].previousSibling.className = "schema_plus";
							removeElement(uls[i]);
						}
						// ------------- on / off

						setDB(this.id);
						sql = "show table status;";
						replaceText(document.getElementById("sqlContents"), document.createTextNode(sql));
						runAjax(sql, this);

					} else {
						this.className = "schema_plus";
						removeElement(this.nextSibling);
					}
				};

				var DBselector = document.getElementById("DBselector");
				var option = document.createElement("option");
				option.appendChild(textNode.cloneNode(false));
				option.value = text;
				DBselector.appendChild(option);

			} else if (queryTarget[0] == "show" && queryTarget[1] == "table") { // =============
				// describe
				li.className = "table_plus";
				var rowNo = String(eval("jsonData.data[1].resultSet[" + i + "].Rows"));
				rowNo += rowNo > 1 ? " rows" : " row";

				var textNode = document.createTextNode(text + " : " + rowNo + "");

				li.onclick = function() {
					if (this.className == "table_plus") {
						this.className = "table_minus";
						setDB(this.parentNode.previousSibling.id);

						// ------------- toggle on / off
						var uls = this.parentNode.getElementsByTagName("ul");
						for ( var i = 0; i < uls.length; i++) {
							uls[i].previousSibling.className = "table_plus";
							removeElement(uls[i]);
						}
						// ------------- on / off
						sql = "describe " + this.id.split("@")[0];
						replaceText(document.getElementById("sqlContents"), document.createTextNode(sql));
						runAjax(sql, this);
					} else {
						this.className = "table_plus";
						removeElement(this.nextSibling);
					}
				};
			} else if (queryTarget[0] == "describe") { // =============
				// describe
				li.className = "minusF";
				var cSize = String(eval("jsonData.data[1].resultSet[" + i + "].Type"));
				var textNode = document.createTextNode(text + " : " + cSize);

				li.onclick = function() {
					offsetI = 1;

					workingTable = this.parentNode.id;
					var rows = lTrim(getText(this)).split(" ")[2];
					var usePaging = document.getElementById("usePaging").checked;
					if (rows > BIGSIZEROW && !usePaging) {
						if (confirm("row count is bigger than " + BIGSIZEROW
								+ ". Do modify recordPerPage. Do you want to continue?")) {
						}
					} else {
						sql = "select * from " + workingTable;

						replaceText(document.getElementById("sqlContents"), document.createTextNode(sql));
						runAjax(sql, '');
					}
				};
			}

			li.appendChild(textNode);
			ul.appendChild(li);
		}
		parent.parentNode.insertBefore(ul, parent.nextSibling);
	}
}

function isHaveTable(name) {
	var YN = false;
	for ( var i = 0; i < jsonData.data[1].resultSet.length; i++) {
		var parent = String(eval("jsonData.data[1].resultSet[" + i + "].parent"));
		if (name == parent) {
			YN = true;
		}
	}
	return YN;
}

function createRetriveTable() {
	var resultSet = document.getElementById("resultSet");

	var retrieveTable = document.createElement("table");
	retrieveTable.id = "retrieveTable";
	if (resultSet != null) {
		removeAllChild(resultSet);
		resultSet.appendChild(retrieveTable);
		mouseAction();
	}

	var retrieveData = document.createElement("tbody");
	retrieveData.id = "retrieveData";
	retrieveTable.appendChild(retrieveData);

	var totalRows = document.createElement("tr");
	totalRows.id = "totalRows";
	totalRows.style.backgroundColor = COLOR_TR_ODD;
	var td = document.createElement("td");
	td.colSpan = jsonData.data[0].columnNames.length + 2;

	var tableName = jsonData.data[2].tableName;
	var rows = jsonData.data[1].resultSet.length;
	rows += jsonData.data[1].resultSet.length > 1 ? " rows" : " row";

	var textNode = document.createTextNode(tableName + " ( " + rows + " )");
	td.appendChild(textNode);

	var btnDelete = document.createElement("input");
	btnDelete.id = "btnDelete";
	btnDelete.type = "button";
	btnDelete.value = "D";
	td.appendChild(btnDelete);

	var btnUpdate = document.createElement("input");
	btnUpdate.id = "btnUpdate";
	btnUpdate.type = "button";
	btnUpdate.value = "U";
	td.appendChild(btnUpdate);

	var btnRetrieve = document.createElement("input");
	btnRetrieve.id = "btnRetrieve";
	btnRetrieve.type = "button";
	btnRetrieve.value = "R";
	td.appendChild(btnRetrieve);

	var btnCreate = document.createElement("input");
	btnCreate.id = "btnCreate";
	btnCreate.type = "button";
	btnCreate.value = "C";
	td.appendChild(btnCreate);

	totalRows.appendChild(td);
	retrieveData.appendChild(totalRows);

	var tr_columns = document.createElement("tr");
	tr_columns.id = "columns";
	tr_columns.style.backgroundColor = COLOR_TR_EVEN;

	var td_status = document.createElement("td");
	var div_status = document.createElement("div");
	div_status.appendChild(document.createTextNode("��"));
	td_status.appendChild(div_status);
	tr_columns.appendChild(td_status);

	var td_rowNo = document.createElement("td");
	var div_rowNo = document.createElement("div");
	div_rowNo.appendChild(document.createTextNode("row No"));
	div_rowNo.id = "label_rowNo";
	td_rowNo.appendChild(div_rowNo);
	tr_columns.appendChild(td_rowNo);
	retrieveData.appendChild(tr_columns);
}

function retrieve(startIdx) {
	if (request.readyState == 4) {
		jsonData = eval('(' + request.responseText + ')');

		createRetriveTable();
		// var retrieveTable = document.getElementById("retrieveTable");
		var retrieveData = document.getElementById("retrieveData");

		textLength = new Array(jsonData.data[0].columnNames.length);

		var tr_columns = document.getElementById("columns");

		var text = "";
		for ( var j = 0; j < jsonData.data[0].columnNames.length; j++) {
			var td = document.createElement("td");
			text = String(jsonData.data[0].columnNames[j]);
			var isF = isForeignKey(text) ? " (FK)" : "";
			textLength[j] = text + isF;

			var textNode = document.createTextNode(text + isF);

			var div = document.createElement("div");
			div.id = "label_" + text;
			div.className = "colresize";
			div.appendChild(textNode);
			td.appendChild(div);

			tr_columns.appendChild(td);
		}
		retrieveData.appendChild(tr_columns);

		// table data
		var offsetR = Number(startIdx) * pagingValue;
		var row_count = jsonData.data[1].resultSet.length;

		var usePaging = document.getElementById("usePaging");
		if (usePaging.checked == true) {
			var temp = Number(offsetR) + Number(pagingValue);
			if (temp < row_count) {
				row_count = temp;
			}
			pageNumbering();
		}

		for ( var i = offsetR; i < row_count; i++) {
			var tr = document.createElement("tr");
			tr.id = "row_" + i;

			var td_btnCRUD = document.createElement("td");
			var input = document.createElement("input");
			input.type = "button";
			input.value = "-";
			input.id = "btn_" + i;
			input.onclick = function() {
				if (this.value == "-") {
					removeData(this);
					this.value = " ";
				} else if (this.value == " ") {
					restoreData(this);
				} else if (this.value == "u") {
					updateData(this);
				}
			};
			input.className = "btnCRUD";
			td_btnCRUD.appendChild(input);
			tr.appendChild(td_btnCRUD);

			var td_rowNo = document.createElement("td");
			td_rowNo.appendChild(document.createTextNode(i + 1));
			tr.appendChild(td_rowNo);

			tr.style.backgroundColor = (i - offsetR) % 2 == 0 ? COLOR_TR_ODD : COLOR_TR_EVEN;

			for ( var j = 0; j < jsonData.data[0].columnNames.length; j++) {
				var dataColumn = document.createElement("td");
				var data = document.createElement("div");
				data.id = jsonData.data[0].columnNames[j] + "_" + i + "x" + j;
				data.style.height = "12px";

				var cName = jsonData.data[0].columnNames[j];
				var text = String(eval("jsonData.data[1].resultSet[" + i + "]." + cName));

				var inputH = document.createElement("input");
				inputH.id = "hiddenData_" + i + "x" + j;
				inputH.setAttribute("type", "hidden");
				inputH.value = text;

				if (textLength[j].length < text.length) {
					textLength[j] = text;
				}

				// ================================= double click for new value
				if (jsonData.data[4].isAuto[j] == "false") {
					data.ondblclick = function() {

						var inputs = this.parentNode.getElementsByTagName("input");

						var newText = prompt("input new value", inputs[0].value);
						if (newText != null) {
							var nTextNode = document.createTextNode(newText);
							replaceText(this, nTextNode);

							var tr = this.parentNode.parentNode;
							var tds = tr.getElementsByTagName("td");

							if (newText == this.previousSibling.value) {
								this.style.color = COLOR_FONT_NORMAL;
							} else {
								this.style.color = COLOR_FONT_UPDATE;
								this.parentNode.parentNode.style.background = COLOR_TR_UPDATE;
							}

							var btn = this.parentNode.parentNode.childNodes[0].childNodes[0];
							btn.value = " ";

							var updateCnt = 0;
							for ( var j = 0; j < jsonData.data[0].columnNames.length; j++) {
								var input = tds[j + 2].childNodes[0].value;
								var div = getText(tds[j + 2].childNodes[1]);
								if (input != div) {
									updateCnt++;
								}
							}

							if (updateCnt == 0) {
								repaintTable(this);
							}
						}
					};
				}

				var textNode = document.createTextNode(text);
				data.appendChild(textNode);
				dataColumn.appendChild(inputH);
				dataColumn.appendChild(data);
				tr.appendChild(dataColumn);
			}
			retrieveData.appendChild(tr);
		}

		newDataCnt = 1;
		newData();

		// tunnigColumnWidth();
	}
}
// ���콺�� ���� �������� ����
function cell_left() {
	var value = false;
	if (event.offsetX < 5 && window.event.srcElement.parentNode.cellIndex > 2) {
		value = true;
	}
	return value;
}
// ���콺�� ���� ���������� ����
function cell_right() {
	var value = false;
	var right = Number(window.event.srcElement.style.width.replace(/[^0-9]/g, '')) + 4;

	if (event.offsetX > right - 5) {
		value = true;
	}
	return value;
}

var mousedown = false; // ���콺�� ���� ����
var originalTrWidth;
var originalTdWidth;
var originalDivWidth;
var targetTr = "";
var targetTd = ""; // ������ ������ targetTd
var targetDiv = "";
var x = 0; // ���콺 �巹���� ������ġ

function mouseAction() {
	var retrieveTable = document.getElementById("retrieveTable");
	var trs = retrieveTable.getElementsByTagName("tr");
	var borderWidth = 2;

	retrieveTable.onmousedown = function() {
		try {
			var now_mousedown = window.event.srcElement;
			if (now_mousedown.className.toUpperCase() == "COLRESIZE") {

				if (cell_left()) {
					now_mousedown = now_mousedown.parentNode.previousSibling.childNodes[0];
				} else if (!cell_right()) {
					return true;// �����ʵ� ���ʵ� �ƴϸ� ������ ���� ����
				}

				mousedown = true;
				targetDiv = now_mousedown;
				targetTd = targetDiv.parentNode;
				targetTr = targetTd.parentNode;
				originalTrWidth = parseInt(targetTr.style.width);
				originalTdWidth = parseInt(targetTd.style.width);
				originalDivWidth = parseInt(targetDiv.style.width);

				x = event.clientX;
			}
		} catch (e) {
			return true;
		}
	};

	// ��������
	retrieveTable.onmousemove = function() {

		try {
			if (window.event.srcElement.className.toUpperCase() == "COLRESIZE" || targetTd != "") {
				if (targetTd.cellIndex == 2 && cell_left()) {
					return false;
				}

				window.event.srcElement.style.cursor = cell_left() || cell_right() ? "col-resize" : "";

				if (mousedown) {
					var distX = event.x - x; // �̵��� ����

					targetTr.style.width = originalTrWidth + parseInt(distX) + "px";
					targetTd.style.width = originalTdWidth + parseInt(distX) + "px";
					targetDiv.style.width = originalDivWidth + parseInt(distX) + "px";

					for ( var i = 2; i < trs.length; i++) {
						var dataTds = trs[i].getElementsByTagName("td");
						var dataDivs = trs[i].getElementsByTagName("div");
						trs[i].style.width = originalTrWidth + parseInt(distX) + "px";
						dataTds[targetTd.cellIndex].style.width = originalTdWidth + parseInt(distX) + "px";
						dataDivs[targetTd.cellIndex - 2].style.width = originalDivWidth + parseInt(distX) + "px";
					}
					alert(trs.length);
					var newdataInputs = trs[trs.length - 1].getElementsByTagName("input");
					alert(newdataInputs.id);
					newdataInputs[targetTd.cellIndex - 2].style.width = originalDivWidth + parseInt(distX) + "px";
					alert(newdataInputs[targetTd.cellIndex - 2].id);
				}
			} else {
				window.event.srcElement.style.cursor = "";
			}
		} catch (e) {
			return true;
		}
	};

	retrieveTable.onmouseup = function() {
		try {
			mousedown = false;
			targetTd = '';
			targetDiv = '';
		} catch (e) {
			return true;
		}
	};

	retrieveTable.onselectstart = function() {
		try {
			if (targetTd != "") {
				return false;
			}
		} catch (e) {
			return true;
		}
	};
}

function isForeignKey(column) {
	var result = false;
	for ( var i = 0; i < jsonData.data[6].foreignKeys.length; i++) {
		if (column == jsonData.data[6].foreignKeys[i].FKCOLUMN_NAME) {
			result = true;
		}
	}
	return result;
}

function repaintTable(object) {
	var grandFather = object.parentNode.parentNode;
	var brothers = countBrothers(grandFather);

	if (brothers % 2 != 0) {
		grandFather.style.backgroundColor = COLOR_TR_ODD;
	} else {
		grandFather.style.backgroundColor = COLOR_TR_EVEN;
	}

	grandFather.style.color = COLOR_FONT_NORMAL;
	grandFather.childNodes[0].childNodes[0].value = "-";
	datas = grandFather.getElementsByTagName("div");

	for ( var i = 0; i < datas.length; i++) {
		datas[i].style.color = COLOR_FONT_NORMAL;
	}
}

function goPK(query, parent) {
	removeElement(parent.nextSibling);
	var schema = document.getElementById("schema").value;
	url = "../servlet/QueryBrowser.do";
	url += "?query=" + query;
	url += schema != "" ? "&schema=" + schema : "";
	url += "&dummy=" + new Date().getTime();

	createRequest();

	request.open("Get", url, true);

	var ul = document.createElement("ul");
	ul.className = "pkList";
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status == 200) {
			var PKData = eval('(' + request.responseText + ')');

			for ( var i = 0; i < PKData.data[1].resultSet.length; i++) {
				var columnName = PKData.data[0].columnNames[0];
				var text = String(eval("PKData.data[1].resultSet[" + i + "]." + columnName));

				var li = document.createElement("li");
				var textNode = document.createTextNode(text);

				li.onclick = function() {
					parent.value = getText(this);
					removeElement(this.parentNode);
				};

				li.appendChild(textNode);
				ul.appendChild(li);
			}

			if (PKData.data[1].resultSet.length > 0) {
				parent.parentNode.insertBefore(ul, parent.nextSibling);
			}
		}
	};

	request.send(null);
}

var newDataCnt = 1;
function newData() {
	var retrieveData = document.getElementById("retrieveData");
	var rowNo = retrieveData.getElementsByTagName("tr").length - 2;

	var newRow = document.createElement("tr");
	newRow.id = "newRow_" + rowNo;
	newRow.style.backgroundColor = COLOR_TR_ODD;

	var columnBtn = document.createElement("td");
	var btnCUD = document.createElement("input"); // button for insert,
	// update, delete
	btnCUD.className = "btnCRUD";
	btnCUD.type = "button";
	btnCUD.value = "+";
	btnCUD.onclick = function() {
		newData();
	};

	columnBtn.appendChild(btnCUD);
	newRow.appendChild(columnBtn);

	var columnSeq = document.createElement("td");
	newRow.appendChild(columnSeq);

	// colInx = column Index
	for ( var colInx = 0; colInx < jsonData.data[0].columnNames.length; colInx++) {
		var newDataColumn = document.createElement("td");

		var newInputData = document.createElement("input");
		newInputData.id = "new_" + jsonData.data[0].columnNames[colInx] + "_" + rowNo + "x" + colInx;

		newInputData.name = "newData_" + rowNo + "x" + colInx;
		newInputData.type = "text";
		newInputData.className = "newInputData";

		newInputData.onkeypress = function() {
			if (event.keyCode == "13") {
				createData(this);
			}
		};

		newInputData.onfocus = function() {
			var retrieveTable = document.getElementById("retrieveTable");
			var inputs = retrieveTable.getElementsByTagName("input");
			for ( var i = 0; i < inputs.length; i++) {
				if (inputs[i].className == "newInputData") {
					removeElement(inputs[i].nextSibling);
				}
			}
		};

		newDataColumn.appendChild(newInputData);

		if (jsonData.data[4].isAuto[colInx] == "true") { // auto incresement
			newInputData.style.background = COLOR_INPUT_AUTO;
			newInputData.disabled = true;
			newInputData.value = parseInt(jsonData.data[4].isAuto[colInx]) + newDataCnt;
			newDataCnt++;
		} else {
			if (isForeignKey(jsonData.data[0].columnNames[colInx])) {

				newInputData.onkeyup = function() {
					var columnNo = countBrothers(this.parentNode);
					var columnFk = jsonData.data[0].columnNames[columnNo - 1];
					var tableFk = jsonData.data[2].tableName;
					var columnPk;
					var tablePk;
					for (i = 0; i < jsonData.data[6].foreignKeys.length; i++) {
						if (jsonData.data[6].foreignKeys[i].FKTABLE_NAME == tableFk
								&& jsonData.data[6].foreignKeys[i].FKCOLUMN_NAME == columnFk) {
							columnPk = jsonData.data[6].foreignKeys[i].PKCOLUMN_NAME;
							tablePk = jsonData.data[6].foreignKeys[i].PKTABLE_NAME;
						}
					}

					sql = "select " + columnPk + " from " + tablePk;
					sql += " where " + columnPk + " like \"" + this.value + escape('%') + "\"";

					if (this.value.length > 0) {
						goPK(sql, this);
					} else {
						removeElement(this.nextSibling);
					}
				};

			}
		}

		newRow.appendChild(newDataColumn);
	}
	retrieveData.appendChild(newRow);
	tunnigColumnWidth();
}

function createData(el) {
	var brothers = countBrothers(el.parentNode.parentNode);
	var rowNo = el.parentNode.parentNode.sectionRowIndex - 2;

	var len = jsonData.data[0].columnNames.length;
	var query = "INSERT INTO " + jsonData.data[2].tableName + " (";

	for ( var j = 0; j < len; j++) {
		query += jsonData.data[0].columnNames[j];
		query += j < len - 1 ? ", " : "";
	}
	query += ") VALUES (";
	for ( var j = 0; j < len; j++) {
		var type = jsonData.data[3].columnsType[j];
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += document.getElementById("new_" + jsonData.data[0].columnNames[j] + "_" + rowNo + "x" + j).value;
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += j < len - 1 ? ", " : "";
	}
	query += ")";

	replaceText(document.getElementById("queryString"), document.createTextNode(query));
}

function removeData(el) {
	var brothers = countBrothers(el.parentNode.parentNode) - 1;

	el.parentNode.parentNode.style.backgroundColor = COLOR_TR_DELETE;

	var len = jsonData.data[0].columnNames.length;
	var query = "DELETE FROM " + jsonData.data[2].tableName + " WHERE ";
	for ( var j = 0; j < len; j++) {
		var type = jsonData.data[3].columnsType[j];
		query += jsonData.data[0].columnNames[j] + " = ";
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += document.getElementById("hiddenData_" + brothers + "x" + j).value;
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += j < len - 1 ? " AND " : "";
	}

	var textNode = document.createTextNode(query);
}

function updateData(el) {
	var rNo = el.parentNode.parentNode.sectionRowIndex - 2;
	var inputs = el.parentNode.parentNode.getElementsByTagName("input");
	var divs = el.parentNode.parentNode.getElementsByTagName("div");

	var len = jsonData.data[0].columnNames.length;
	var query = "UPDATE " + jsonData.data[2].tableName + " SET ";

	for ( var j = 0; j < len; j++) {
		var type = jsonData.data[3].columnsType[j];
		query += jsonData.data[0].columnNames[j] + " = ";
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += getText(divs[j]);
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += j < len - 1 ? ", " : "";
	}

	query += " WHERE ";
	for ( var j = 0; j < len; j++) {
		var type = jsonData.data[3].columnsType[j];
		query += jsonData.data[0].columnNames[j] + " = ";
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += inputs[j + 1].value;
		query += findInArray(type, [ '1', '12' ]) ? "'" : "";
		query += j < len - 1 ? " AND " : "";
	}

	var textNode = document.createTextNode(query);
}

function restoreData(el) {
	var inputs = el.parentNode.parentNode.getElementsByTagName("input");
	var divs = el.parentNode.parentNode.getElementsByTagName("div");
	var len = jsonData.data[0].columnNames.length;

	for ( var j = 0; j < len; j++) {
		replaceText(divs[j], document.createTextNode(inputs[j + 1].value));
	}

	repaintTable(el);
}

function tunnigColumnWidth() {
	var trs = document.getElementById("retrieveTable").getElementsByTagName("tr");
	var borderWidth = 2;
	for ( var i = 1; i < trs.length; i++) {
		var trWidth = 0;
		if (trs[i].id == "columns" || trs[i].id == "row_" + (i - 2) || trs[i].id == "newRow_" + (i - 2)) {
			// (autoComplete)
			var tds = trs[i].getElementsByTagName("td");
			var divs = trs[i].getElementsByTagName("div");
			var inputs = trs[i].getElementsByTagName("input");

			for ( var j = 2; j < tds.length; j++) {
				tds[j].style.width = textLength[j - 2].length * 12 + borderWidth * 2 + "px";
				trWidth += textLength[j - 2].length * 12 + borderWidth * 2;
				if (trs[i].id == "columns") {
					divs[j].style.width = textLength[j - 2].length * 12 + "px";
				} else if (trs[i].id == "row_" + (i - 2)) {
					divs[j - 2].style.width = textLength[j - 2].length * 12 + "px";
				} else if (trs[i].id == "newRow_" + (i - 2)) {
					inputs[j - 1].style.width = textLength[j - 2].length * 12 + "px";
				}
			}
		}
		trWidth += 18 + 45 + tds.length + 1;
		trs[i].style.width = trWidth + "px";
	}
}

function findInArray(param, target) {
	var YN = false;
	for ( var i = 0; i < target.length; i++) {
		if (param == target[i]) {
			YN = true;
		}
	}
	return YN;
}

function pageNumbering() {
	var lengthOfData = rowCount;
	// jsonData.data[1].resultSet.length;
	var pageCnt = 10;

	pagingValue = document.getElementById("pagingValue").value;
	var pages = document.createElement("div");
	pages.id = "pages";

	var resultSet = document.getElementById("resultSet");
	resultSet.appendChild(pages);

	// ========================================================= First page (<<)
	var pageFirst = document.createElement("span");
	pageFirst.id = "pageFirst";
	pageFirst.className = "pageNo";
	pageFirst.onclick = function() {
		if (pageBand > 0) {
			pageBand = 0;
			retrieve(pageBand * pageCnt);
		} else {
			alert("no pre page");
		}
	};
	pageFirst.appendChild(document.createTextNode("�� "));
	pages.appendChild(pageFirst);

	// ======================================================= previous page (<)
	var pagePrev = document.createElement("span");
	pagePrev.id = "pagePrev";
	pagePrev.className = "pageNo";
	pagePrev.onclick = function() {
		if (pageBand > 0) {
			pageBand--;
			retrieve(pageBand * pageCnt);
		} else {
			alert("no pre page");
		}
	};
	pagePrev.appendChild(document.createTextNode("��"));
	pages.appendChild(pagePrev);

	// =========================================================== page numbers
	var lastPageNo = Math.ceil(lengthOfData / pagingValue);
	var sPage = pageBand * pageCnt + 1;
	var ePage = sPage + pageCnt - 1;

	if (ePage > lastPageNo) {
		ePage = lastPageNo;
	}

	pages.style.display = ePage < 2 ? "none" : "block";

	for ( var i = sPage; i <= ePage; i++) {
		var pageNo = document.createElement("span");
		pageNo.id = "pageNo_" + i;
		pageNo.className = "pageNo";
		pageNo.onclick = function() {
			pageBand = parseInt((getText(this) - 1) / pageCnt);

			if (!document.getElementById("useAjax").checked) {
				sql = "select * from " + workingTable;
				offsetI = getText(this);
				runAjax(sql, '');
			} else {
				retrieve(getText(this) - 1);
			}
		};
		var textNode = document.createTextNode(i);
		pageNo.appendChild(textNode);
		pages.appendChild(pageNo);
	}

	// =========================================================== next page (>)
	var pageNext = document.createElement("span");
	pageNext.id = "pageNext";
	pageNext.className = "pageNo";
	pageNext.onclick = function() {
		if ((pageBand + 1) * pageCnt < lastPageNo) {
			pageBand++;
			retrieve(pageBand * pageCnt);
		} else {
			alert("no next page");
		}
	};
	pageNext.appendChild(document.createTextNode("��"));
	pages.appendChild(pageNext);

	// ========================================================== last page (>>)
	var pageLast = document.createElement("span");
	pageLast.id = "pageLast";
	pageLast.className = "pageNo";
	pageLast.onclick = function() {
		if ((pageBand + 1) * pageCnt < lastPageNo) {
			pageBand = Math.ceil((lastPageNo / pageCnt)) - 1;
			retrieve(lastPageNo - 1);
		} else {
			alert("no next page");
		}
	};
	pageLast.appendChild(document.createTextNode("��"));
	pages.appendChild(pageLast);
}

var DBKeyWords = [ "ADD", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT",
		"BINARY", "BLOB", "BOTH", "BY", "CALL", "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", "COLLATE",
		"COLUMN", "CONDITION", "CONNECTION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT_DATE",
		"CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR",
		"DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DELAYED", "DELETE",
		"DESC", "DESCRIBE", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", "DROP", "DUAL", "EACH",
		"ELSE", "ELSEIF", "ENCLOSED", "ESCAPED", "EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", "FLOAT", "FLOAT4",
		"FLOAT8", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GOTO", "GRANT", "GROUP", "HAVING", "HIGH_PRIORITY",
		"HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT",
		"INSENSITIVE", "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO", "IS",
		"ITERATE", "JOIN", "KEY", "KEYS", "KILL", "LABEL", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LINES",
		"LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MATCH",
		"MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES",
		"NATURAL", "NOT", "NO_WRITE_TO_BINLOG", "NULL", "NUMERIC", "ON", "OPTIMIZE", "OPTION", "OPTIONALLY", "OR",
		"ORDER", "OUT", "OUTER", "OUTFILE", "PRECISION", "PRIMARY", "PROCEDURE", "PURGE", "RAID0", "READ", "READS",
		"REAL", "REFERENCES", "REGEXP", "RELEASE", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESTRICT", "RETURN",
		"REVOKE", "RIGHT", "RLIKE", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR",
		"SET", "SHOW", "SMALLINT", "SONAME", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING",
		"SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SSL", "STARTING", "STRAIGHT_JOIN", "TABLE",
		"TERMINATED", "THEN", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER", "TRUE", "UNDO", "UNION",
		"UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE", "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP",
		"VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "WHEN", "WHERE", "WHILE", "WITH", "WRITE", "X509",
		"XOR", "YEAR_MONTH", "ZEROFILL" ];

// ========================= excel ==========================================

function goExcel(path) {
	createRequest();
	url = "../servlet/ExcelUploader.do";
	url += "?path=" + path;
	url += "&dummy=" + new Date().getTime();

	request.open("Get", url, true);

	request.onreadystatechange = function() {
		spreadSheet();
	};

	request.send(null);
}

function spreadSheet() {

	if (request.readyState == 4) {
		eData = eval('(' + request.responseText + ')');

		var table = document.createElement("table");
		table.id = "table001";
		table.border = "1";

		var tBody = document.createElement("tbody");
		tBody.id = "tBody001";

		for ( var i = 0; i < eData.data.length; i++) {
			var row = eData.data[i];
			var tr = document.createElement("tr");

			for ( var j = 0; j < row.length; j++) {
				var td = document.createElement("td");
				td.dblclick = function() {
					alert(getText(this));
					// clearText(this);
				};

				var text = String(eval("eData.data[" + i + "][" + j + "].cell"));
				var textNode = document.createTextNode(text);
				td.appendChild(textNode);
				tr.appendChild(td);

			}
			tBody.appendChild(tr);
		}

		table.appendChild(tBody);
		var resultSet = document.getElementById("resultSet");
		if (resultSet != null) {
			clearText(resultSet);
			resultSet.appendChild(table);
		}
	}
}

function xlsUpload() {
	var filePathXLS = document.getElementById("filePathXLS");
	goExcel(filePathXLS.value);
}

function changeLayout(object) {
	var layoutSelector = document.getElementById("layoutSelector");
	var headerMenu = document.getElementById("headerMenu");
	var schemata = document.getElementById("schemata");
	var queryContents = document.getElementById("queryContents");
	var outputContent = document.getElementById("outputContent");
	var pages = document.getElementById("pages");

	headerMenu.className = "headerMenu_01";
	if (object.id == "layout01") {
		schemata.className = "schemata_01";
		queryContents.className = "queryContents_01";
		outputContent.className = "outputContent_01";
		layoutSelector.style.backgroundImage = "url('./_img/type01_s.jpg')";
	} else if (object.id == "layout02") {
		schemata.className = "schemata_02";
		queryContents.className = "queryContents_02";
		outputContent.className = "outputContent_02";
		layoutSelector.style.backgroundImage = "url('./_img/type02_s.jpg')";
	} else if (object.id == "layout03") {
		schemata.className = "schemata_03";
		queryContents.className = "queryContents_03";
		outputContent.className = "outputContent_03";
		layoutSelector.style.backgroundImage = "url('./_img/type03_s.jpg')";
	} else if (object.id == "layout04") {
		schemata.className = "schemata_04";
		queryContents.className = "queryContents_04";
		outputContent.className = "outputContent_04";
		layoutSelector.style.backgroundImage = "url('./_img/type04_s.jpg')";
	}
}
// ========================= windows ========================================

var layoutEx = "off";
var helpEx = "off";
var excelTemp = "off";

window.onload = function() {

	var usePaging = document.getElementById("usePaging");
	usePaging.onclick = function() {
		if (this.checked) {
			document.getElementById("pagingValue").disabled = false;
			document.getElementById("useAjax").disabled = false;
		} else {
			document.getElementById("pagingValue").disabled = true;
			document.getElementById("useAjax").disabled = true;
		}
	};

	pagingValue = Number(document.getElementById("pagingValue").value);

	var schemataTemp = document.getElementById("schemataTemp");
	sql = "show databases";
	replaceText(document.getElementById("sqlContents"), document.createTextNode(sql));
	runAjax(sql, schemataTemp);

	var queryString = document.getElementById("queryString");
	queryString.onkeyup = function() {
		offsetI = 1;
		var finalChar = getText(this).replace(/^\s+|\s+$/g, "");
		/*
		 * queryStringInputed = getText(this).split(" ");
		 * 
		 * var innerHTML; for ( var i = 0; i < queryStringInputed.length; i++) {
		 * if (findInArray(queryStringInputed[i], DBKeyWords)) { innerHTML += '<span
		 * class="keyWord">' + queryStringInputed[i] + '</span>'; } else {
		 * innerHTML += queryStringInputed[i]; } } this.innerHTML = innerHTML;
		 */

		if (event.keyCode == "13" && event.ctrlKey == true && finalChar[finalChar.length - 1] == ";") {
			sql = getText(this);
			replaceText(document.getElementById("sqlContents"), document.createTextNode(sql));
			runAjax(sql, "");
		}
	};

	var pagePrev = document.getElementById("pagePrev");
	var pageNext = document.getElementById("pageNext");
	var pageLast = document.getElementById("pageLast");

	var btnXLSUp = document.getElementById("btnXLSUp");
	btnXLSUp.onclick = function() {
		xlsUpload();
	};

	var excelUpload = document.getElementById("excelUpload");
	excelUpload.onclick = function() {
		var excelUploadEx = document.getElementById("excelUploadEx");
		if (excelTemp == "off") {
			excelUploadEx.style.display = "block";
			excelTemp = "on";
		} else {
			excelUploadEx.style.display = "none";
			excelTemp = "off";
		}
	};

	var help = document.getElementById("help");
	help.onclick = function() {
		var helpList = document.getElementById("helpList");
		if (helpEx == "off") {
			helpList.style.display = "block";
			helpEx = "on";
		} else {
			helpList.style.display = "none";
			helpEx = "off";
		}
	};

	var layoutList = document.getElementById("layoutList");
	layoutList = layoutList.getElementsByTagName("li");

	for ( var i = 0; i < layoutList.length; i++) {
		layoutList[i].onclick = function() {
			changeLayout(this);
			this.parentNode.style.display = "none";
			layoutEx = "off";
		};
	}

	var layoutSelector = document.getElementById("layoutSelector");
	layoutSelector.onclick = function() {
		var layoutList = document.getElementById("layoutList");
		if (layoutEx == "off") {
			layoutList.style.display = "block";
			layoutEx = "on";
		} else {
			layoutList.style.display = "none";
			layoutEx = "off";
		}
	};

	changeLayout(document.getElementById("layout02"));

	var filePathXLS = document.getElementById("filePathXLS");
	var fakeFileInput = document.getElementById("fakeFileInput");
	filePathXLS.onchange = function() {
		fakeFileInput.value = this.value;
	};
};
/*
 * window.event.srcElement.style.width window.event.clientX window.event.offsetX
 * window.event.layerX window.event.pageX window.event.screenX
 */

/*
 * function setABLayout(object, top, left, width, height, index, display) {
 * object.style.position = "absolute"; object.style.top = top + "px";
 * object.style.left = left + "px"; object.style.width = width;
 * object.style.height = height; object.style.margin = "0px";
 * object.style.zIndex = index; object.style.display = display; }
 * 
 * function changeLayout_old(object) { var layoutSelector =
 * document.getElementById("layoutSelector"); var screenW =
 * document.body.clientWidth; var screenH = document.body.clientHeight; var
 * headerMenu = document.getElementById("headerMenu"); var schemata =
 * document.getElementById("schemata"); var queryContents =
 * document.getElementById("queryContents"); var outputContent =
 * document.getElementById("outputContent"); var pages =
 * document.getElementById("pages");
 * 
 * setABLayout(headerMenu, "0px", "0px", "100%", "32px", "0", "block");
 * 
 * if (object.id == "layout01") { setABLayout(schemata, "32", "0", "384px",
 * "240px", "0", "block"); setABLayout(queryContents, "32", "384",
 * (parseInt(screenW) - 384) + "px", "240px", "0", "block");
 * setABLayout(outputContent, "272", "0", "100%", (parseInt(screenH) - 272) +
 * "px", "0", "block");
 * 
 * layoutSelector.style.backgroundImage = "url('./_img/type01_s.jpg')"; } else
 * if (object.id == "layout02") { setABLayout(schemata, "32", "0", "384px",
 * (parseInt(screenH) - 32) + "px", "0", "block"); setABLayout(queryContents,
 * "32", "384", (parseInt(screenW) - 384) + "px", "240px", "0", "block");
 * setABLayout(outputContent, "272", "384", (parseInt(screenW) - 384) + "px",
 * (parseInt(screenH) - 272) + "px", "0", "block");
 * 
 * layoutSelector.style.backgroundImage = "url('./_img/type02_s.jpg')"; } else
 * if (object.id == "layout03") { setABLayout(schemata, "32", "0", "384px",
 * "240px", "0", "none"); setABLayout(queryContents, "32", "0", "100%", "240px",
 * "0", "block"); setABLayout(outputContent, "272", "0", "100%",
 * (parseInt(screenH) - 272) + "px", "0", "block");
 * 
 * layoutSelector.style.backgroundImage = "url('./_img/type03_s.jpg')"; } else
 * if (object.id == "layout04") { setABLayout(schemata, "272", "0", "384px",
 * (parseInt(screenH) - 272) + "px", "0", "block"); setABLayout(queryContents,
 * "32", "0", "100%", "240px", "0", "block"); setABLayout(outputContent, "272",
 * "384", (parseInt(screenW) - 384) + "px", (parseInt(screenH) - 272) + "px",
 * "0", "block");
 * 
 * layoutSelector.style.backgroundImage = "url('./_img/type04_s.jpg')"; } }
 */
